package com.ruoyi.system.util;

import org.springframework.web.multipart.MultipartFile;
import org.apache.commons.io.IOUtils;

import java.io.*;
import java.util.Base64;

public class Base64ToMultipartFile implements MultipartFile {
    private final byte[] content;
    private final String name;
    private final String contentType;

    public Base64ToMultipartFile(String base64) {
        String[] parts = base64.split(",");
        this.contentType = parts[0].split(":")[1].split(";")[0];
        this.content = Base64.getDecoder().decode(parts[1]);
        this.name = "file_" + System.currentTimeMillis(); // 自定义文件名
    }

    @Override
    public String getName() { return name; }
    @Override
    public String getOriginalFilename() { return name; }
    @Override
    public String getContentType() { return contentType; }
    @Override
    public boolean isEmpty() { return content == null || content.length == 0; }
    @Override
    public long getSize() { return content.length; }
    @Override
    public byte[] getBytes() { return content; }
    @Override
    public InputStream getInputStream() { return new ByteArrayInputStream(content); }
    @Override
    public void transferTo(File dest) throws IOException, IllegalStateException {
        try (FileOutputStream fos = new FileOutputStream(dest)) {
            fos.write(content);
        }
    }
}
